var AV = require('leanengine');
var async = require('async');
var log4js = require('log4js');
var logger = log4js.getLogger('normal');

exports.formatProduct = function(pids){
    var promise = new AV.Promise();
    //将商品表中的规格中的价格最低的整个规格id作为一个该商品的默认规格字段信息
    var Product = AV.Object.extend("Product");
    var query = new AV.Query(Product);
    query.limit(1000);
    if(pids){
        if(pids === true){
            //查询全部
        }else{
            query.containedIn('objectId',pids);
        }
    }else{
        //geek 模式
        //该模式下会将所有的没有格式化过的数据进行一次格式化
        //query.doesNotExist('minSpecName');
        //组合查询
        var q1 = new AV.Query(Product);
        q1.doesNotExist('minSpecName');
        var q2 = new AV.Query(Product);
        q2.equalTo("minSpecName", '');
        query = AV.Query.or(q1, q2);
        logger.debug('geek 模式下，格式化商品信息');
    }
    //query.equalTo('objectId','209');
    query.find({
        success: function(results) {
            // 处理返回的结果数据
            async.mapSeries(results,function(object,next){
                var specs = object.get('spec');
                var grp = 100000;
                var index = 0;
                var minSpecName = '';
                for(var i in specs){
                    var spec = specs[i];
                    //库存格式化
                    var inventory = spec.inventory;
                    inventory = '' + inventory ;
                    inventory = parseInt(inventory);
                    if(isNaN(inventory) || inventory < 0){
                        inventory = 0;
                    }
                    spec.inventory = inventory;
                    //价格格式化
                    var grprice = spec.grprice;
                    var f = parseFloat(grprice);
                    spec.grprice = f;
                    if(f < grp){
                        grp = f;
                        index = i;
                        minSpecName = spec.name;
                    }

                    //销量格式化
                    var salenum = spec.salenum;
                    salenum = '' + salenum ;
                    salenum = parseInt(salenum);
                    if(isNaN(salenum) || salenum < 0){
                        salenum = 0;
                    }
                    spec.salenum = salenum;

                    specs[i] = spec;
                }
                //设置规格
                object.set('spec',specs);
                //设置最优惠的规格编号
                object.set('minSpec', index);
                //设置最优惠的规格名称
                object.set('minSpecName', minSpecName);
                //设置最优惠的单价
                object.set('minPrice',grp);
                //设置规格的库存信息


                var GoodsComment = AV.Object.extend("GoodsComment");


                var countQuery = new AV.Query(GoodsComment);
                countQuery.equalTo("pid", object.id);
                countQuery.count().then(function(c){
                    object.set('commentCount', c);
                    object.save().then(function(res){
                        next(null,'ok');
                    });
                });
                ////评论数量格式化
                //var commentCount = object.commentCount || 0;
                //commentCount = '' + commentCount ;
                //commentCount = parseInt(commentCount);
                //if(isNaN(commentCount) || commentCount < 0){
                //    commentCount = 0;
                //}


            },function(err,res){
                if(err){
                    console.log(err);
                    promise.reject('error');
                }else{
                    promise.resolve('ok');
                }
            });

        },
        error: function(error) {
            console.log("Error: " + error.code + " " + error.message);
            promise.reject('error');
        }
    });

    return promise;
}

exports.cleanOrder = function(){
    var promise = new AV.Promise();
    var Order = AV.Object.extend("Order");
    var counter = new AV.Query(Order);
    counter.containedIn('status',[-1,-2]);
    //counter.doesNotExist('address');
    counter.count().then(function(count){
        console.log(count);
        var arr = [];

        for(var i = 0 ; i < count / 100 ; i++){
            arr[i] = '0';
        }

        async.eachSeries(arr,function(ele,callback){
            var query = new AV.Query(Order);
            query.containedIn('status',[-1,-2]);
            //query.doesNotExist('address');
            query.destroyAll().then(function(res){
                callback(null,res);
            }).catch(function(err){
                callback(err);
            });
        },function(err,res){
            if(err)
                promise.reject(err);
            else
                promise.resolve(res);
        });
    });


    return promise;
};

exports.closeOrder = function(){
    var promise = new AV.Promise();
    var Order = AV.Object.extend("Order");
    var counter = new AV.Query(Order);
    counter.containedIn('status',[2500,3000,4000]);
    //counter.doesNotExist('address');
    counter.greaterThan('paytime',1445702400000);//2015-10-25 00 00 00
    counter.lessThan('paytime',1446109200000);//2015-10-28 00 00 00
    counter.count().then(function(count){
        console.log(count);
        var arr = [];

        for(var i = 0 ; i < count / 100 ; i++){
            arr[i] = '0';
        }

        async.eachSeries(arr,function(ele,callback){
            var query = new AV.Query(Order);
            query.containedIn('status',[2500,3000,4000]);
            counter.greaterThan('paytime',1445702400000);//2015-10-25 00 00 00
            counter.lessThan('paytime',1446109200000);//2015-10-25 00 00 00
            //query.doesNotExist('address');
            query.find().then(function(res){
                async.eachSeries(res,function(e,callback2){
                    //e.set('status',9000);
                    e.set('closed',true);
                    e.set('status',9000);
                    e.save().then(function(e2){
                        callback2(null,e2);
                    }).catch(function(err){callback2(err);});

                },function(err,r){
                    if(err)
                        callback(err);
                    else
                        callback(null,r);
                });


                //callback(null,res);
            }).catch(function(err){
                callback(err);
            });
        },function(err,res){
            if(err)
                promise.reject(err);
            else
                promise.resolve(res);
        });
    });


    return promise;
};

exports.formatComment = function(){
    var promise = new AV.Promise();
    var GoodsComment = AV.Object.extend("GoodsComment");
    var query = new AV.Query(GoodsComment);
    query.limit(1000);
    query.equalTo('syncStatus',1);
    query.doesNotExist('score');
    //query.count().then(function(c){
    //    console.log(c);
    //    promise.resolve(c);
    //});
    query.find().then(function(res){
        async.eachSeries(res,function(ele,callback){
            ele.set('score',5);
            ele.save().then(function(r){
                callback(null,r);
            }).catch(function(e){
                callback(e);
            });
        },function(err,res){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(res);
            }
        });
    }).catch(function(err){
        callback(err);
    });
    return promise;
}